package com.logger;

import android.util.Log;

import com.logger.handlers.AHandler;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 处理异步打印日志
 * Created by chenxunlin01 on 2016/1/16.
 */

public class LoggerAsync extends Thread {

    private static volatile LoggerAsync async = new LoggerAsync();
    private static Object mutex = new Object();
    /**
     * 日志事件队列
     */
    private static Queue<LoggerPocket> pockets = new ConcurrentLinkedQueue<>();

    /**
     * 添加到队列中
     *
     * @param pocket
     */
    public static void offer(LoggerPocket pocket) {
        pockets.offer(pocket);
        if (async == null || !async.isAlive()) {
            synchronized (mutex) {
                if (async == null || !async.isAlive()) {
                    async = new LoggerAsync();
                    async.start();
                }
            }
        }
    }

    @Override

    public void run() {
        try {
            while (!isInterrupted()) {
                LoggerPocket pocket = null;
                Thread.sleep(100);
                while ((pocket = pockets.poll()) != null) {
                    for (AHandler handler : pocket.getHandlers()) {
                        handler.doHandler(pocket.getMessage());
                    }
                }
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
